package com.cs2.volunteerpostbackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cs2.volunteerpostbackend.dao.CommentMapper;
import com.cs2.volunteerpostbackend.dao.ImageMapper;
import com.cs2.volunteerpostbackend.dao.MomentImageMapper;
import com.cs2.volunteerpostbackend.po.Comment;
import com.cs2.volunteerpostbackend.po.Image;
import com.cs2.volunteerpostbackend.po.MomentImage;
import com.cs2.volunteerpostbackend.service.CommentService;
import com.cs2.volunteerpostbackend.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private MomentImageMapper momentImageMapper;

    @Override
    public Image saveImage(MultipartFile imageFile, String posterId, String momentId) throws IOException {
        // 创建图片实体
        Image image = new Image();
        image.setFileName(System.currentTimeMillis() + "_" + imageFile.getOriginalFilename());
        image.setUploadTime(System.currentTimeMillis());

        // 获取项目根目录
        String projectRoot = System.getProperty("user.dir");

        System.out.println("projectRoot:" + projectRoot);

        // 构建存储路径: resources/images/{posterId}/{momentId}/
        String basePath = projectRoot + "/volunteer-post-backend/src/main/resources/images/" + posterId + "/" + momentId + "/";
        File baseDir = new File(basePath);

        // 创建目录（如果不存在）
        if (!baseDir.exists()) {
            System.out.println("目录不存在");
            baseDir.mkdirs();
            System.out.println("目录创建完成");
        }

        // 生成文件名（避免重复）
        String fileName = image.getFileName();
        String filePath = basePath + fileName;

        // 保存图片到文件系统
        imageFile.transferTo(new File(filePath));

        // 设置图片路径和URL
        image.setFilePath(filePath);
        image.setUrl("/images/" + posterId + "/" + momentId + "/" + fileName);

        // 保存图片记录到数据库
        imageMapper.insert(image);

        return image;
    }

    @Override
    public void saveMomentImageRelation(String momentId, String imageId) {
        MomentImage momentImage = new MomentImage();
        momentImage.setMomentId(momentId);
        momentImage.setImageId(imageId);

        momentImageMapper.insert(momentImage);
    }

    @Override
    public List<Image> getImagesByMomentId(String momentId) {
        return imageMapper.selectImagesByMomentId(momentId);
    }

    @Override
    public List<Image> saveImages(List<MultipartFile> imageFiles, String posterId, String momentId) throws IOException {
        // 批量保存图片
        for (MultipartFile imageFile : imageFiles) {
            if (imageFile != null && !imageFile.isEmpty()) {
                saveImage(imageFile, posterId, momentId);
            }
        }
        return getImagesByMomentId(momentId);
    }
    
    @Override
    public Image downloadImageFromUrl(String imageUrl, String posterId, String momentId) throws IOException {
        // 创建图片实体
        Image image = new Image();
        String fileName = System.currentTimeMillis() + "_downloaded_" + getFileNameFromUrl(imageUrl);
        image.setFileName(fileName);
        image.setUploadTime(System.currentTimeMillis());

        // 获取项目根目录
        String projectRoot = System.getProperty("user.dir");

        // 构建存储路径: resources/images/{posterId}/{momentId}/
        String basePath = projectRoot + "/volunteer-post-backend/src/main/resources/images/" + posterId + "/" + momentId + "/";
        File baseDir = new File(basePath);

        // 创建目录（如果不存在）
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }

        // 完整文件路径
        String filePath = basePath + fileName;
        
        // 从URL下载图片
        downloadFileFromUrl(imageUrl, filePath);

        // 设置图片路径和URL
        image.setFilePath(filePath);
        image.setUrl("/images/" + posterId + "/" + momentId + "/" + fileName);

        // 保存图片记录到数据库
        imageMapper.insert(image);

        return image;
    }
    
    /**
     * 从URL下载文件到指定路径
     * @param imageUrl 图片URL
     * @param filePath 保存路径
     * @throws IOException
     */
    private void downloadFileFromUrl(String imageUrl, String filePath) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        
        try (InputStream inputStream = connection.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(filePath)) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
    
    /**
     * 从URL中提取文件名
     * @param imageUrl 图片URL
     * @return 文件名
     */
    private String getFileNameFromUrl(String imageUrl) {
        try {
            String path = new URL(imageUrl).getPath();
            String fileName = path.substring(path.lastIndexOf('/') + 1);
            return fileName.isEmpty() ? "image.jpg" : fileName;
        } catch (Exception e) {
            return "image.jpg";
        }
    }
}